<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha256-wiz7ZSCn/btzhjKDQBms9Hx4sSeUYsDrTLg7roPstac=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.css" integrity="sha256-6cQIC71/iBIYXFK+0RHAvwmjwWzkWd+r7v/BX3/vZDc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/green/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"sumumm.github.io","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.19.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":true,"height":300},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="可不可以通过一个驱动控制多个设备？怎么实现？若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:type" content="article">
<meta property="og:title" content="LV06-03-chrdev-08-1个驱动兼容多个设备">
<meta property="og:url" content="https://sumumm.github.io/post/c439ab2a.html">
<meta property="og:site_name" content="苏木">
<meta property="og:description" content="可不可以通过一个驱动控制多个设备？怎么实现？若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/02IMX6ULL%E5%B9%B3%E5%8F%B0/LV06-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/LV06-03-chrdev-08-1%E4%B8%AA%E9%A9%B1%E5%8A%A8%E5%85%BC%E5%AE%B9%E5%A4%9A%E4%B8%AA%E8%AE%BE%E5%A4%87/img/image-20241226105838093.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/02IMX6ULL%E5%B9%B3%E5%8F%B0/LV06-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/LV06-03-chrdev-08-1%E4%B8%AA%E9%A9%B1%E5%8A%A8%E5%85%BC%E5%AE%B9%E5%A4%9A%E4%B8%AA%E8%AE%BE%E5%A4%87/img/image-20241226112813160.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/02IMX6ULL%E5%B9%B3%E5%8F%B0/LV06-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/LV06-03-chrdev-08-1%E4%B8%AA%E9%A9%B1%E5%8A%A8%E5%85%BC%E5%AE%B9%E5%A4%9A%E4%B8%AA%E8%AE%BE%E5%A4%87/img/image-20241226151337208.png">
<meta property="article:published_time" content="2024-12-26T14:38:11.000Z">
<meta property="article:modified_time" content="2025-06-13T16:25:57.050Z">
<meta property="article:author" content="苏木">
<meta property="article:tag" content="LV06-驱动开发">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/02IMX6ULL%E5%B9%B3%E5%8F%B0/LV06-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/LV06-03-chrdev-08-1%E4%B8%AA%E9%A9%B1%E5%8A%A8%E5%85%BC%E5%AE%B9%E5%A4%9A%E4%B8%AA%E8%AE%BE%E5%A4%87/img/image-20241226105838093.png">


<link rel="canonical" href="https://sumumm.github.io/post/c439ab2a.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":"","permalink":"https://sumumm.github.io/post/c439ab2a.html","path":"post/c439ab2a.html","title":"LV06-03-chrdev-08-1个驱动兼容多个设备"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>LV06-03-chrdev-08-1个驱动兼容多个设备 | 苏木</title>
  








    <script src="/js/browser_tools_disable.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<!-- hexo injector head_end start --><link rel="stylesheet" href="https://unpkg.com/hexo-next-tags-plus@latest/lib/tag_plus.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">苏木</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">我的学习之路</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>苏木的家</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类页<span class="badge">42</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档页<span class="badge">673</span></a></li><li class="menu-item menu-item-flink"><a href="/flink/" rel="section"><i class="fa fa-link fa-fw"></i>友人帐</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E6%A6%82%E8%BF%B0"><span class="nav-text">一、概述</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E8%83%8C%E6%99%AF"><span class="nav-text">1. 背景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%8F%AF%E4%BB%A5%E6%9C%89%E5%93%AA%E4%BA%9B%E6%96%B9%E5%BC%8F"><span class="nav-text">2. 可以有哪些方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-inode%E7%BB%93%E6%9E%84%E4%BD%93"><span class="nav-text">3. inode结构体</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%811%E4%B8%AAcdev%E8%AE%BE%E5%A4%87"><span class="nav-text">二、1个cdev设备</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E6%80%8E%E4%B9%88%E5%AE%9E%E7%8E%B0%EF%BC%9F"><span class="nav-text">1. 怎么实现？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-demo%E5%AE%9E%E7%8E%B0"><span class="nav-text">2. demo实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E5%BC%80%E5%8F%91%E6%9D%BF%E6%B5%8B%E8%AF%95"><span class="nav-text">3. 开发板测试</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E5%A4%9A%E4%B8%AAcdev%E8%AE%BE%E5%A4%87"><span class="nav-text">三、多个cdev设备</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E6%80%8E%E4%B9%88%E5%AE%9E%E7%8E%B0%EF%BC%9F-1"><span class="nav-text">1. 怎么实现？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-%E8%AE%BE%E5%A4%87%E5%8F%B7%E7%94%B3%E8%AF%B7%E4%B8%8E%E6%B3%A8%E9%94%80"><span class="nav-text">1.1 设备号申请与注销</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-%E8%AE%BE%E5%A4%87%E6%B3%A8%E5%86%8C%E4%B8%8E%E6%B3%A8%E9%94%80"><span class="nav-text">1.2 设备注册与注销</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-%E7%B1%BB%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E9%94%80%E6%AF%81"><span class="nav-text">1.3 类的创建与销毁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-4-%E8%AE%BE%E5%A4%87%E5%88%9B%E5%BB%BA%E4%B8%8E%E9%94%80%E6%AF%81"><span class="nav-text">1.4 设备创建与销毁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5-%E6%80%8E%E4%B9%88%E5%8C%BA%E5%88%86%E4%B8%8D%E5%90%8C%E7%9A%84%E8%AE%BE%E5%A4%87%EF%BC%9F"><span class="nav-text">1.5 怎么区分不同的设备？</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-demo%E5%AE%9E%E7%8E%B0-1"><span class="nav-text">2. demo实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E5%BC%80%E5%8F%91%E6%9D%BF%E6%B5%8B%E8%AF%95-1"><span class="nav-text">3. 开发板测试</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="苏木"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">苏木</p>
  <div class="site-description" itemprop="description">莫道桑榆晚，为霞尚满天</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">673</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">42</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">43</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/sumumm" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sumumm" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://sumumm.github.io/post/c439ab2a.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="苏木">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苏木">
      <meta itemprop="description" content="莫道桑榆晚，为霞尚满天">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="LV06-03-chrdev-08-1个驱动兼容多个设备 | 苏木">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          LV06-03-chrdev-08-1个驱动兼容多个设备
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2024-12-26 22:38:11" itemprop="dateCreated datePublished" datetime="2024-12-26T22:38:11+08:00">2024-12-26</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">嵌入式开发</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/02IMX6ULL%E5%B9%B3%E5%8F%B0/" itemprop="url" rel="index"><span itemprop="name">02IMX6ULL平台</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/02IMX6ULL%E5%B9%B3%E5%8F%B0/LV06-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">LV06-驱动开发</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>7.5k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>27 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>可不可以通过一个驱动控制多个设备？怎么实现？若笔记中有错误或者不合适的地方，欢迎批评指正😃。</p>
<span id="more"></span>

<!-- Photo: https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/02IMX6ULL%E5%B9%B3%E5%8F%B0/LV06-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/LV06-03-chrdev-08-1%E4%B8%AA%E9%A9%B1%E5%8A%A8%E5%85%BC%E5%AE%B9%E5%A4%9A%E4%B8%AA%E8%AE%BE%E5%A4%87/img/ -->

<details class="folding-tag" blue><summary> 点击查看使用工具及版本 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" rowspan="5">PC端开发环境</td>        <td align="center" width=150px>Windows</td>        <td align="left">Windows11</td>    </tr>    <tr>        <td align="center">Ubuntu</td>        <td align="left">Ubuntu20.04.2的64位版本</td>      </tr>    <tr>        <td align="center">VMware® Workstation 17 Pro</td>        <td align="left">17.6.0 build-24238078</td>      </tr>    <tr>        <td align="center">终端软件</td>        <td align="left">MobaXterm(Professional Edition v23.0 Build 5042 (license))</td>    </tr>    <tr>        <td align="center">Win32DiskImager</td>        <td align="left">Win32DiskImager v1.0</td>      </tr>    <tr>        <td align="center" rowspan="3">Linux开发板环境</td>        <td align="center">Linux开发板</td>        <td align="left">正点原子 i.MX6ULL Linux 阿尔法开发板</td>      </tr>    <tr>        <td align="center">uboot</td>        <td align="left">NXP官方提供的uboot，使用的uboot版本为U-Boot 2019.04</td>      </tr>    <tr>        <td align="center">linux内核</td>        <td align="left">linux-4.19.71(NXP官方提供)</td>      </tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看本文参考资料 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center">分类</td>        <td align="center">网址</td>        <td align="center">说明</td>    </tr>    <tr>        <td align="center" rowspan="5">官方网站</td>        <td align="left"><a href="https://www.arm.com/" target="_blank">https://www.arm.com/</a></td>        <td align="left">ARM官方网站，在这里我们可以找到Cotex-Mx以及ARMVx的一些文档</td>    </tr>    <tr>        <td align="left"><a href="https://www.nxp.com.cn/" target="_blank">https://www.nxp.com.cn/ </a></td>        <td align="left">NXP官方网站</td>    </tr>    <tr>        <td align="left"><a href="https://www.nxpic.org.cn/" target="_blank">https://www.nxpic.org.cn/</a></td><td align="left">NXP 官方社区</td>    </tr>    <tr>        <td align="left"><a href="https://u-boot.readthedocs.io/en/latest/" target="_blank">https://u-boot.readthedocs.io/en/latest/</a></td><td align="left">u-boot官网</td>    </tr>    <tr>        <td align="left"><a href="https://www.kernel.org/" target="_blank">https://www.kernel.org/</a></td><td align="left">linux内核官网</td>    </tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看相关文件下载 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center">分类</td>        <td align="center">网址</td>        <td align="center">说明</td>    </tr>    <tr>        <td align="center" rowspan="3">NXP</td>        <td align="left"><a href="https://github.com/nxp-imx" target="_blank">https://github.com/nxp-imx</a></td>        <td align="left">NXP imx开发资源GitHub组织，里边会有u-boot和linux内核的仓库</td>    </tr>    <tr>        <td align="left"><a href="https://github.com/nxp-imx/linux-imx/releases/tag/v4.19.71" target="_blank">nxp-imx/linux-imx/releases/tag/v4.19.71</a></td>        <td align="left">NXP linux内核仓库tags中的v4.19.71</td>    </tr>    <tr>        <td align="left"><a href="https://github.com/nxp-imx/uboot-imx/releases/tag/rel_imx_4.19.35_1.1.0" target="_blank">nxp-imx/uboot-imx/releases/tag/rel_imx_4.19.35_1.1.0</a></td>        <td align="left">NXP u-boot仓库tags中的rel_imx_4.19.35_1.1.0</td>    </tr>    <tr>        <td align="center" rowspan="2">I.MX6ULL</td>        <td align="left"><a href="https://www.nxp.com.cn/docs/en/data-sheet/IMX6ULLIEC.pdf" target="_blank">i.MX 6ULL Applications Processors for Industrial Products</a></td>        <td align="left">I.MX6ULL 芯片手册（datasheet，可以在线查看）</td>    </tr>    <tr>        <td align="left"><a href="https://www.nxp.com.cn/webapp/Download?colCode=IMX6ULLRM&lang_cd=zh" target="_blank">i.MX 6ULL Applications ProcessorReference Manual</a></td>        <td align="left">I.MX6ULL 参考手册（下载后才能查看，需要登录NXP官网）</td>    </tr>    <tr>        <td align="center" rowspan="3">Source Code</td>        <td align="left"><a href="https://elixir.bootlin.com/linux/latest/source" target="_blank">https://elixir.bootlin.com/linux/latest/source</a></td>        <td align="left">linux kernel源码</td>    </tr>    <tr>        <td align="left"><a href="https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/?h=v4.19.71&id=e7d2672c66e4d3675570369bf20856296da312c4" target="_blank">kernel/git/stable/linux.git - Linux kernel stable tree</a></td>        <td align="left">linux kernel源码(官网,tag 4.19.71)</td>    </tr>    <tr>        <td align="left"><a href="https://elixir.bootlin.com/u-boot/latest/source" target="_blank">https://elixir.bootlin.com/u-boot/latest/source</a></td>        <td align="left">uboot源码</td>    </tr></table>
              </div>
            </details>

<h1 id="一、概述"><a href="#一、概述" class="headerlink" title="一、概述"></a><font size=3>一、概述</font></h1><h2 id="1-背景"><a href="#1-背景" class="headerlink" title="1. 背景"></a><font size=3>1. 背景</font></h2><p>在Linux内核中，主设备号用于标识设备对应的驱动程序，告诉Linux内核使用哪一个驱动程序为该设备服务。但是， 次设备号表示了同类设备的各个设备。每个设备的功能都是不一样的。如何能够用一个驱动程序去控制各种设备呢？</p>
<p>很明显，首先，我们可以根据次设备号，来区分各种设备；其次，就是提到过的file结构体的私有数据成员private_data。 我们可以通过该成员来指向不同的设备，不难想到为什么只有open函数和close函数的形参才有file结构体， 因为驱动程序第一个执行的是操作就是open，通过open函数就可以控制我们想要驱动的底层硬件。</p>
<h2 id="2-可以有哪些方式"><a href="#2-可以有哪些方式" class="headerlink" title="2. 可以有哪些方式"></a><font size=3>2. 可以有哪些方式</font></h2><p>有两种方式：</p>
<ul>
<li>（1）一个cdev对象管理多个设备；</li>
<li>（2）多个cdev对象，每个cdev对象管理一个设备。</li>
</ul>
<h2 id="3-inode结构体"><a href="#3-inode结构体" class="headerlink" title="3. inode结构体"></a><font size=3>3. inode结构体</font></h2><p>前面学习这个inode结构体的时候有这么两个成员：<a target="_blank" rel="noopener" href="https://elixir.bootlin.com/linux/v4.19.71/source/include/linux/fs.h#L593">fs.h - include&#x2F;linux&#x2F;fs.h - <em>struct inode</em></a></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">inode</span> &#123;</span></span><br><span class="line">	<span class="comment">// ......</span></span><br><span class="line">	<span class="type">dev_t</span>			i_rdev;</span><br><span class="line">	<span class="comment">// ......</span></span><br><span class="line">	<span class="class"><span class="keyword">union</span> &#123;</span></span><br><span class="line">		<span class="class"><span class="keyword">struct</span> <span class="title">pipe_inode_info</span>	*<span class="title">i_pipe</span>;</span></span><br><span class="line">		<span class="class"><span class="keyword">struct</span> <span class="title">block_device</span>	*<span class="title">i_bdev</span>;</span></span><br><span class="line">		<span class="class"><span class="keyword">struct</span> <span class="title">cdev</span>		*<span class="title">i_cdev</span>;</span></span><br><span class="line">		<span class="type">char</span>			*i_link;</span><br><span class="line">		<span class="type">unsigned</span>		i_dir_seq;</span><br><span class="line">	&#125;;</span><br><span class="line">	<span class="comment">// ......</span></span><br><span class="line">&#125; __randomize_layout;</span><br></pre></td></tr></table></figure>

<ul>
<li>dev_t i_rdev： 表示设备文件的结点，这个域实际上包含了设备号。</li>
<li>struct cdev *i_cdev： struct cdev是内核的一个内部结构，它是用来表示字符设备的，当inode结点指向一个字符设备文件时，此域为一个指向inode结构的指针。</li>
</ul>
<p>一个含有设备号，一个指向字符设备，我们可以利用这两个成员来区分不同设备的。后面会说明这两个成员怎么用。</p>
<h1 id="二、1个cdev设备"><a href="#二、1个cdev设备" class="headerlink" title="二、1个cdev设备"></a><font size=3>二、1个cdev设备</font></h1><h2 id="1-怎么实现？"><a href="#1-怎么实现？" class="headerlink" title="1. 怎么实现？"></a><font size=3>1. 怎么实现？</font></h2><p>1个cdev的话，我们只需要一个cdev对象，一个类，但是设备号需要创建多个，并且根据不同的次设备号创建多个设备节点，用来控制不同的缓冲区。</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/02IMX6ULL%E5%B9%B3%E5%8F%B0/LV06-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/LV06-03-chrdev-08-1%E4%B8%AA%E9%A9%B1%E5%8A%A8%E5%85%BC%E5%AE%B9%E5%A4%9A%E4%B8%AA%E8%AE%BE%E5%A4%87/img/image-20241226105838093.png" alt="image-20241226105838093"  />

<p>不同的设备节点对应不同的次设备号，我们可以在open的时候根据设备节点，找到设备号，根据次设备号来对应不同的缓冲区。那另一个问题来了，怎么在open的时候获取次设备号？</p>
<p><strong>inode结构体中，对于设备文件的设备号会被保存到其成员i_rdev中</strong>，所以：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">static</span> <span class="type">int</span> <span class="title function_">sdev_open</span><span class="params">(<span class="keyword">struct</span> inode *inode, <span class="keyword">struct</span> file *file)</span></span><br><span class="line">&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">switch</span> (MINOR(inode-&gt;i_rdev))</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="number">0</span>:</span><br><span class="line">        &#123;</span><br><span class="line">            file-&gt;private_data = &amp;g_sdev_child[<span class="number">0</span>]; <span class="comment">//设置私有数据</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">        &#123; </span><br><span class="line">            file-&gt;private_data = &amp;g_sdev_child[<span class="number">1</span>]; <span class="comment">//设置私有数据</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">        &#123;</span><br><span class="line">            file-&gt;private_data = &amp;g_sdev_child[<span class="number">0</span>]; <span class="comment">//设置私有数据</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    printk(<span class="string">&quot;This is sdev_open!inode-&gt;i_rdev=%d, minor=%d\n&quot;</span>, inode-&gt;i_rdev, MINOR(inode-&gt;i_rdev));</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>为什么？这个我没有去深究inode-&gt;i_rdev中怎么吧设备号保存下来的，我查到在使用mknod命令创建节点的时候会调用这个函数<a target="_blank" rel="noopener" href="https://elixir.bootlin.com/linux/v4.19.71/source/fs/inode.c#L1982">inode.c - fs&#x2F;inode.c - <em>init_special_inode</em></a>：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">init_special_inode</span><span class="params">(<span class="keyword">struct</span> inode *inode, <span class="type">umode_t</span> mode, <span class="type">dev_t</span> rdev)</span></span><br><span class="line">&#123;</span><br><span class="line">	inode-&gt;i_mode = mode;</span><br><span class="line">	<span class="keyword">if</span> (S_ISCHR(mode)) &#123;</span><br><span class="line">		inode-&gt;i_fop = &amp;def_chr_fops;</span><br><span class="line">		inode-&gt;i_rdev = rdev;</span><br><span class="line">	&#125; </span><br><span class="line">    <span class="comment">//......</span></span><br><span class="line">&#125;</span><br><span class="line">EXPORT_SYMBOL(init_special_inode);</span><br></pre></td></tr></table></figure>

<p>会发现这里是有赋值的，大概应该是这里，不过自动创建节点的函数中怎么赋值的我追了一下代码，没找到，这里先不管了，知道它保存的是设备号就是了，后面有需要了再详细去了解。</p>
</blockquote>
<h2 id="2-demo实现"><a href="#2-demo实现" class="headerlink" title="2. demo实现"></a><font size=3>2. demo实现</font></h2><p>直接看我的gitee仓库吧：<a target="_blank" rel="noopener" href="https://gitee.com/sumumm/imx6ull-driver-demo/tree/master/04_chrdev_basic/09_chrdev_more_dev_1c">04_chrdev_basic&#x2F;09_chrdev_more_dev_1c · 苏木&#x2F;imx6ull-driver-demo - 码云 - 开源中国</a></p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/02IMX6ULL%E5%B9%B3%E5%8F%B0/LV06-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/LV06-03-chrdev-08-1%E4%B8%AA%E9%A9%B1%E5%8A%A8%E5%85%BC%E5%AE%B9%E5%A4%9A%E4%B8%AA%E8%AE%BE%E5%A4%87/img/image-20241226112813160.png" alt="image-20241226112813160"  />

<p>直接执行make即可进行编译，编译完成后会得到对应的驱动程序和应用测试程序。</p>
<details class="folding-tag" blue><summary> 点击查看详情 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/init.h&gt;</span> <span class="comment">/* module_init module_exit */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/kernel.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/module.h&gt;</span> <span class="comment">/* MODULE_LICENSE */</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/fs.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/cdev.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/uaccess.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;./timestamp_autogenerated.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;./version_autogenerated.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CHRDEV_NAME <span class="string">&quot;sdev&quot;</span>    <span class="comment">/* 设备名,cat /proc/devices 查看与设备号的对应关系 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CLASS_NAME  <span class="string">&quot;sclass&quot;</span>  <span class="comment">/* 类名，在 /sys/class 中显示的名称 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> DEVICE_NAME <span class="string">&quot;sdevice&quot;</span> <span class="comment">/* 设备节点名，在 /sys/class/class_name/ 中显示的名称以及 /dev/ 下显示的节点名 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> BUFSIZE     32        <span class="comment">/* 设置最大偏移量为32 */</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CHRDEV_CNT (2)        <span class="comment">/* 设备数量 */</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CMD_TEST0 _IO(<span class="string">&#x27;S&#x27;</span>, 0)</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CMD_TEST1 _IOW(<span class="string">&#x27;S&#x27;</span>, 1, int)</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CMD_TEST2 _IOR(<span class="string">&#x27;S&#x27;</span>, 2, int)</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CMD_TEST3 _IOW(<span class="string">&#x27;S&#x27;</span>, 3, int)</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> __<span class="title">CMD_TEST</span>&#123;</span></span><br><span class="line">	<span class="type">int</span> a;</span><br><span class="line">	<span class="type">int</span> b;</span><br><span class="line">	<span class="type">int</span> c;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> __<span class="title">CHAR_DEVICE</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="type">dev_t</span> dev_num;         <span class="comment">// 定义dev_t类型（32位大小）的变量dev_num,用来存放设备号</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">cdev</span> <span class="title">s_cdev</span>;</span>    <span class="comment">// 定义cdev结构体类型的变量scdev</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="keyword">class</span> *<span class="keyword">class</span>;</span>   <span class="comment">// 定于struct class *类型结构体变量 class，表示要创建的类</span></span><br><span class="line">&#125; _CHAR_DEVICE;</span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> __<span class="title">CHAR_DEVICE_CHILD</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">device</span> *<span class="title">device</span>;</span> <span class="comment">// 设备</span></span><br><span class="line">    <span class="type">char</span> buf[BUFSIZE];     <span class="comment">// 设置数据存储数组mem</span></span><br><span class="line">&#125;_CHAR_DEVICE_CHILD;</span><br><span class="line"></span><br><span class="line">_CHAR_DEVICE g_sdev;  <span class="comment">//定义一个 g_sdev 结构体变量，只包含一个cdev对象</span></span><br><span class="line">_CHAR_DEVICE_CHILD g_sdev_child[CHRDEV_CNT] = &#123;<span class="number">0</span>&#125;; <span class="comment">// 一个cdev对象要管理的 CHRDEV_CNT 个设备</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="type">int</span> <span class="title function_">sdev_open</span><span class="params">(<span class="keyword">struct</span> inode *inode, <span class="keyword">struct</span> file *file)</span></span><br><span class="line">&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">switch</span> (MINOR(inode-&gt;i_rdev))</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="number">0</span>:</span><br><span class="line">        &#123;</span><br><span class="line">            file-&gt;private_data = &amp;g_sdev_child[<span class="number">0</span>]; <span class="comment">//设置私有数据</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">        &#123; </span><br><span class="line">            file-&gt;private_data = &amp;g_sdev_child[<span class="number">1</span>]; <span class="comment">//设置私有数据</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">        &#123;</span><br><span class="line">            file-&gt;private_data = &amp;g_sdev_child[<span class="number">0</span>]; <span class="comment">//设置私有数据</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    printk(<span class="string">&quot;This is sdev_open!inode-&gt;i_rdev=%d, minor=%d\n&quot;</span>, inode-&gt;i_rdev, MINOR(inode-&gt;i_rdev));</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="type">ssize_t</span> <span class="title function_">sdev_read</span><span class="params">(<span class="keyword">struct</span> file *file, <span class="type">char</span> __user *buf, <span class="type">size_t</span> size, <span class="type">loff_t</span> *off)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="type">loff_t</span> offset = *off; <span class="comment">// 将读取数据的偏移量赋值给loff_t类型变量p</span></span><br><span class="line">    <span class="type">size_t</span> count = size;</span><br><span class="line">    _CHAR_DEVICE_CHILD *pDev=(_CHAR_DEVICE_CHILD *)file-&gt;private_data; <span class="comment">//在write函数中读取private_data</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (offset &gt; BUFSIZE)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (count &gt; BUFSIZE - offset)</span><br><span class="line">    &#123;</span><br><span class="line">        count = BUFSIZE - offset;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (copy_to_user(buf, pDev-&gt;buf + offset, count))</span><br><span class="line">    &#123; </span><br><span class="line">        <span class="comment">// 将mem中的值写入buf，并传递到用户空间</span></span><br><span class="line">        printk(<span class="string">&quot;copy_to_user error!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; BUFSIZE; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        printk(<span class="string">&quot;buf[%d] %c\n&quot;</span>, i, pDev-&gt;buf[i]); <span class="comment">// 将mem中的值打印出来</span></span><br><span class="line">    &#125;</span><br><span class="line">    printk(<span class="string">&quot;read offset is %llu, count is %d\n&quot;</span>, offset, count);</span><br><span class="line">    *off = *off + count; <span class="comment">// 更新偏移值</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> count;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="type">ssize_t</span> <span class="title function_">sdev_write</span><span class="params">(<span class="keyword">struct</span> file *file, <span class="type">const</span> <span class="type">char</span> __user *buf, <span class="type">size_t</span> size, <span class="type">loff_t</span> *off)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="type">loff_t</span> offset = *off; <span class="comment">// 将读取数据的偏移量赋值给loff_t类型变量p</span></span><br><span class="line">    <span class="type">size_t</span> count = size;</span><br><span class="line">    _CHAR_DEVICE_CHILD *pDev=(_CHAR_DEVICE_CHILD *)file-&gt;private_data; <span class="comment">//在write函数中读取private_data</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (offset &gt; BUFSIZE)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (count &gt; BUFSIZE - offset)</span><br><span class="line">    &#123;</span><br><span class="line">        count = BUFSIZE - offset;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (copy_from_user(pDev-&gt;buf + offset, buf, count))</span><br><span class="line">    &#123; </span><br><span class="line">        <span class="comment">// 将buf中的值，从用户空间传递到内核空间</span></span><br><span class="line">        printk(<span class="string">&quot;copy_to_user error \n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; BUFSIZE; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        printk(<span class="string">&quot;buf[%d] %c\n&quot;</span>, i, pDev-&gt;buf[i]); <span class="comment">// 将mem中的值打印出来</span></span><br><span class="line">    &#125;</span><br><span class="line">    printk(<span class="string">&quot;write offset is %llu, count is %d\n&quot;</span>, offset, count); <span class="comment">// 打印写入的值</span></span><br><span class="line">    *off = *off + count;                         <span class="comment">// 更新偏移值</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> count;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="type">int</span> <span class="title function_">sdev_release</span><span class="params">(<span class="keyword">struct</span> inode *inode, <span class="keyword">struct</span> file *file)</span></span><br><span class="line">&#123;</span><br><span class="line">    printk(<span class="string">&quot;This is sdev_release!\n&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="type">loff_t</span> <span class="title function_">sdev_llseek</span><span class="params">(<span class="keyword">struct</span> file *file, <span class="type">loff_t</span> offset, <span class="type">int</span> whence)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">loff_t</span> new_offset = <span class="number">0</span>; <span class="comment">// 定义loff_t类型的新的偏移值</span></span><br><span class="line">    <span class="keyword">switch</span> (whence)    <span class="comment">// 对lseek函数传递的whence参数进行判断</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">case</span> SEEK_SET:</span><br><span class="line">            <span class="keyword">if</span> (offset &lt; <span class="number">0</span> || offset &gt; BUFSIZE)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">return</span> -EINVAL; <span class="comment">// EINVAL=22 表示无效参数</span></span><br><span class="line">            &#125;</span><br><span class="line">            new_offset = offset; <span class="comment">// 如果whence参数为SEEK_SET，则新偏移值为offset</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> SEEK_CUR:</span><br><span class="line">            <span class="keyword">if</span> ((file-&gt;f_pos + offset &lt; <span class="number">0</span>) || (file-&gt;f_pos + offset &gt; BUFSIZE))</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">return</span> -EINVAL;</span><br><span class="line">            &#125;</span><br><span class="line">            new_offset = file-&gt;f_pos + offset; <span class="comment">// 如果whence参数为SEEK_CUR，则新偏移值为file-&gt;f_pos + offset，file-&gt;f_pos为当前的偏移值</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> SEEK_END:</span><br><span class="line">            <span class="keyword">if</span> (file-&gt;f_pos + offset &lt; <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">return</span> -EINVAL;</span><br><span class="line">            &#125;</span><br><span class="line">            new_offset = BUFSIZE + offset; <span class="comment">// 如果whence参数为SEEK_END，则新偏移值为BUFSIZE + offset，BUFSIZE为最大偏移量</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    file-&gt;f_pos = new_offset; <span class="comment">// 更新file-&gt;f_pos偏移值</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> new_offset;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="type">long</span> <span class="title function_">sdev_ioctl</span><span class="params">(<span class="keyword">struct</span> file *file, <span class="type">unsigned</span> <span class="type">int</span> cmd, <span class="type">unsigned</span> <span class="type">long</span> arg)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> val = <span class="number">0</span>;<span class="comment">//定义 int 类型向应用空间传递的变量 val</span></span><br><span class="line">    <span class="keyword">switch</span>(cmd)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">case</span> CMD_TEST0:</span><br><span class="line">            printk(<span class="string">&quot;this is CMD_TEST0\n&quot;</span>);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> CMD_TEST1:</span><br><span class="line">            printk(<span class="string">&quot;this is CMD_TEST1\n&quot;</span>);</span><br><span class="line">            printk(<span class="string">&quot;arg is %ld\n&quot;</span>,arg);<span class="comment">//打印应用空间传递来的 arg 参数</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> CMD_TEST2:</span><br><span class="line">            val = <span class="number">1</span>;<span class="comment">//将要传递的变量 val 赋值为 1</span></span><br><span class="line">            printk(<span class="string">&quot;this is CMD_TEST2\n&quot;</span>);</span><br><span class="line">            <span class="keyword">if</span>(copy_to_user((<span class="type">int</span> *)arg, &amp;val, <span class="keyword">sizeof</span>(val)) != <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="comment">//通过 copy_to_user 向用户空间传递数据</span></span><br><span class="line">                printk(<span class="string">&quot;copy_to_user error \n&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> CMD_TEST3:</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="class"><span class="keyword">struct</span> __<span class="title">CMD_TEST</span> <span class="title">cmd_test3</span> =</span> &#123;<span class="number">0</span>&#125;;</span><br><span class="line">            <span class="keyword">if</span> (copy_from_user(&amp;cmd_test3, (<span class="type">int</span> *)arg, <span class="keyword">sizeof</span>(cmd_test3)) != <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                printk(<span class="string">&quot;copy_from_user error\n&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            printk(<span class="string">&quot;cmd_test3.a = %d\n&quot;</span>, cmd_test3.a);</span><br><span class="line">            printk(<span class="string">&quot;cmd_test3.b = %d\n&quot;</span>, cmd_test3.b);</span><br><span class="line">            printk(<span class="string">&quot;cmd_test3.c = %d\n&quot;</span>, cmd_test3.c);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="class"><span class="keyword">struct</span> <span class="title">file_operations</span> <span class="title">cdev_ops</span> =</span> &#123;</span><br><span class="line">    .owner = THIS_MODULE,<span class="comment">//将owner字段指向本模块，可以避免在模块的操作正在被使用时卸载该模块</span></span><br><span class="line">	.open = sdev_open,</span><br><span class="line">	.read = sdev_read,</span><br><span class="line">	.write = sdev_write,</span><br><span class="line">	.release = sdev_release,</span><br><span class="line">    .llseek = sdev_llseek,</span><br><span class="line">    .unlocked_ioctl = sdev_ioctl,</span><br><span class="line">&#125;; <span class="comment">// 定义file_operations结构体类型的变量g_cdev_dev_ops</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 模块入口函数</span></span><br><span class="line"><span class="type">static</span> <span class="type">int</span> __init <span class="title function_">chrdev_more_dev_1c_demo_init</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="type">int</span> ret = <span class="number">0</span>;          <span class="comment">// 定义int类型的变量ret，用来判断函数返回值</span></span><br><span class="line">    <span class="type">int</span> major = <span class="number">0</span>, minor = <span class="number">0</span>; <span class="comment">// 定义int类型的主设备号major和次设备号minor</span></span><br><span class="line">    printk(<span class="string">&quot;*** [%s:%d]Build Time: %s %s, git version:%s ***\n&quot;</span>, __FUNCTION__,</span><br><span class="line">           __LINE__, KERNEL_KO_DATE, KERNEL_KO_TIME, KERNEL_KO_VERSION);</span><br><span class="line">    printk(<span class="string">&quot;chrdev_more_dev_1c_demo module init!\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    ret = alloc_chrdev_region(&amp;g_sdev.dev_num, <span class="number">0</span>, CHRDEV_CNT, CHRDEV_NAME); <span class="comment">// 自动获取设备号，设备名为chrdev_name</span></span><br><span class="line">    <span class="keyword">if</span> (ret &lt; <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        printk(<span class="string">&quot;alloc_chrdev_region is error!\n&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    printk(<span class="string">&quot;alloc_register_region is ok!\n&quot;</span>);</span><br><span class="line">    major = MAJOR(g_sdev.dev_num); <span class="comment">// 使用MAJOR()函数获取主设备号</span></span><br><span class="line">    minor = MINOR(g_sdev.dev_num); <span class="comment">// 使用MINOR()函数获取次设备号</span></span><br><span class="line">    printk(<span class="string">&quot;major is %d, minor is %d !\n&quot;</span>, major, minor);</span><br><span class="line"></span><br><span class="line">    cdev_init(&amp;g_sdev.s_cdev, &amp;cdev_ops); <span class="comment">// 使用cdev_init()函数初始化g_sdev.s_cdev结构体，并链接到 cdev_ops 结构体</span></span><br><span class="line">    g_sdev.s_cdev.owner = THIS_MODULE;          <span class="comment">// 将owner字段指向本模块，可以避免在模块的操作正在被使用时卸载该模块</span></span><br><span class="line">    ret = cdev_add(&amp;g_sdev.s_cdev, g_sdev.dev_num, CHRDEV_CNT); <span class="comment">// 使用cdev_add()函数进行字符设备的添加</span></span><br><span class="line">    <span class="keyword">if</span> (ret &lt; <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        printk(<span class="string">&quot;cdev_add is error !\n&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    printk(<span class="string">&quot;cdev_add is ok!CHRDEV_CNT=%d\n&quot;</span>, CHRDEV_CNT);</span><br><span class="line"></span><br><span class="line">    g_sdev.class = class_create(THIS_MODULE, CLASS_NAME);          <span class="comment">// 使用class_create进行类的创建，类名称为 class_dev</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 这里还是需要创建多个设备的</span></span><br><span class="line">    <span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; CHRDEV_CNT; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        g_sdev_child[i].device = device_create(g_sdev.class, <span class="literal">NULL</span>, g_sdev.dev_num + i, <span class="literal">NULL</span>, <span class="string">&quot;%s%d&quot;</span>,DEVICE_NAME, i); <span class="comment">// 使用device_create进行设备的创建，设备名称为 device_dev</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 模块出口函数</span></span><br><span class="line"><span class="type">static</span> <span class="type">void</span> __exit <span class="title function_">chrdev_more_dev_1c_demo_exit</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">// 需要注意的是， 字符设备的注册要放在申请字符设备号之后，</span></span><br><span class="line">    <span class="comment">// 字符设备的删除要放在释放字符驱动设备号之前。</span></span><br><span class="line">    cdev_del(&amp;g_sdev.s_cdev);                <span class="comment">// 使用cdev_del()函数进行字符设备的删除</span></span><br><span class="line">    unregister_chrdev_region(g_sdev.dev_num, CHRDEV_CNT); <span class="comment">// 释放字符驱动设备号</span></span><br><span class="line">    <span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; CHRDEV_CNT; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        device_destroy(g_sdev.class, g_sdev.dev_num + i); <span class="comment">// 删除创建的设备</span></span><br><span class="line">    &#125;</span><br><span class="line">    class_destroy(g_sdev.class);           <span class="comment">// 删除创建的类</span></span><br><span class="line">    printk(<span class="string">&quot;chrdev_more_dev_1c_demo exit!\n&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">module_init(chrdev_more_dev_1c_demo_init); <span class="comment">// 将__init定义的函数指定为驱动的入口函数</span></span><br><span class="line">module_exit(chrdev_more_dev_1c_demo_exit); <span class="comment">// 将__exit定义的函数指定为驱动的出口函数</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 模块信息(通过 modinfo chrdev_more_dev_1c_demo 查看) */</span></span><br><span class="line">MODULE_LICENSE(<span class="string">&quot;GPL v2&quot;</span>);            <span class="comment">/* 源码的许可证协议 */</span></span><br><span class="line">MODULE_AUTHOR(<span class="string">&quot;sumu&quot;</span>);               <span class="comment">/* 字符串常量内容为模块作者说明 */</span></span><br><span class="line">MODULE_DESCRIPTION(<span class="string">&quot;Description&quot;</span>);   <span class="comment">/* 字符串常量内容为模块功能说明 */</span></span><br><span class="line">MODULE_ALIAS(<span class="string">&quot;module&#x27;s other name&quot;</span>); <span class="comment">/* 字符串常量内容为模块别名 */</span></span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h2 id="3-开发板测试"><a href="#3-开发板测试" class="headerlink" title="3. 开发板测试"></a><font size=3>3. 开发板测试</font></h2><ul>
<li>（1）加载驱动</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">insmod chrdev_more_dev_1c_demo.ko</span><br></pre></td></tr></table></figure>

<ul>
<li>（2）查看设备节点</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ls /dev/sdevice* -alh</span><br></pre></td></tr></table></figure>

<p>会看到有如下打印信息：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">crw-rw----    1 0        root      246,   0 Jan  1 00:00 /dev/sdevice0</span><br><span class="line">crw-rw----    1 0        root      246,   1 Jan  1 00:00 /dev/sdevice1</span><br></pre></td></tr></table></figure>

<p>在创建设备节点的时候命名就是&#x2F;dev&#x2F;sdeviceN，所以这里是0和1两个设备节点，他们会对应不同的缓冲区。</p>
<ul>
<li>（3）向设备节点写入数据</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">echo 123456789 &gt; /dev/sdevice0</span><br><span class="line">echo 987654321 &gt; /dev/sdevice1</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">或者使用应用测试程序</span></span><br><span class="line">./xxx_demo_app.out /dev/sdevice 1 x # 从x位置读取</span><br><span class="line">./xxx_demo_app.out /dev/sdevice 2 x # 从x位置写入</span><br><span class="line">./xxx_demo_app.out /dev/sdevice 3 x # x为任意值</span><br></pre></td></tr></table></figure>

<ul>
<li>（4）从设备节点读取数据</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">cat /dev/sdevice0</span><br><span class="line">cat /dev/sdevice1</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">或者使用应用测试程序</span></span><br><span class="line">./xxx_demo_app.out /dev/sdevice 1 x # 从x位置读取</span><br><span class="line">./xxx_demo_app.out /dev/sdevice 2 x # 从x位置写入</span><br><span class="line">./xxx_demo_app.out /dev/sdevice 3 x # x为任意值</span><br></pre></td></tr></table></figure>

<h1 id="三、多个cdev设备"><a href="#三、多个cdev设备" class="headerlink" title="三、多个cdev设备"></a><font size=3>三、多个cdev设备</font></h1><h2 id="1-怎么实现？-1"><a href="#1-怎么实现？-1" class="headerlink" title="1. 怎么实现？"></a><font size=3>1. 怎么实现？</font></h2><p>我们现在有多个设备，他们的主设备号一样，次设备号不同，他们也可以使用不同的cdev设备对象，都需要进行注册。但是他们都属于同一个类，所以我们只需要创建一个类就可以了。</p>
<ul>
<li>1、设备号申请的时候要直接连续申请多个；</li>
<li>2、向内核注册新字符设备的时候，每个设备都要注册；</li>
<li>3、创建类的时候只需要创建一个；</li>
<li>4、创建设备的时候需要创建多个设备；</li>
<li>5、删除设备的时候需要删除多个；</li>
<li>6、删除字符设备对象的时候需要删除多个。</li>
</ul>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/02IMX6ULL%E5%B9%B3%E5%8F%B0/LV06-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/LV06-03-chrdev-08-1%E4%B8%AA%E9%A9%B1%E5%8A%A8%E5%85%BC%E5%AE%B9%E5%A4%9A%E4%B8%AA%E8%AE%BE%E5%A4%87/img/image-20241226151337208.png" alt="image-20241226151337208"  />

<h3 id="1-1-设备号申请与注销"><a href="#1-1-设备号申请与注销" class="headerlink" title="1.1 设备号申请与注销"></a><font size=3>1.1 设备号申请与注销</font></h3><p>设备号身申请的时候不需要申请多次，只需要申请一次，并且指定要申请的设备数量即可，以 alloc_chrdev_region 为例：<a target="_blank" rel="noopener" href="https://elixir.bootlin.com/linux/v4.19.71/source/fs/char_dev.c#L245">char_dev.c - fs&#x2F;char_dev.c - <em>alloc_chrdev_region</em></a>：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alloc_chrdev_region(&amp;parentDevno, <span class="number">0</span>, dev_cnt, NEWCHAR_DEV_NAME); <span class="comment">/* 申请设备号 */</span></span><br></pre></td></tr></table></figure>

<p>这样我们就可以得到一个“父”设备号devno，这个设备号包含主设备号和次设备号：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">major = MAJOR(parentDevno); <span class="comment">/* 获取分配号的主设备号 */</span></span><br><span class="line">minor = MINOR(parentDevno); <span class="comment">/* 获取分配号的次设备号 */</span></span><br></pre></td></tr></table></figure>

<p>我们可以从这个设备号中获取到dev_cnt个“子”设备号，”子“设备号怎么获取呢？这样来获取：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; dev_cnt; i++)</span><br><span class="line">&#123;</span><br><span class="line">    devno[i] = MKDEV(major, minor + i);</span><br><span class="line">&#125;</span><br><span class="line">...</span><br><span class="line"><span class="comment">// 或者</span></span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; dev_cnt; i++)</span><br><span class="line">&#123;</span><br><span class="line">    devno[i] = parentDevno + i;</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p>注销设备号的时候，直接注销多个设备即可：<a target="_blank" rel="noopener" href="https://elixir.bootlin.com/linux/v4.19.71/source/fs/char_dev.c#L320">char_dev.c - fs&#x2F;char_dev.c - <em>unregister_chrdev_region</em></a></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 注销设备号（将会删除 /proc/devices 中的设备号和对应的名称记录) */</span></span><br><span class="line">unregister_chrdev_region(devno, dev_cnt);</span><br></pre></td></tr></table></figure>

<h3 id="1-2-设备注册与注销"><a href="#1-2-设备注册与注销" class="headerlink" title="1.2 设备注册与注销"></a><font size=3>1.2 设备注册与注销</font></h3><p>设备注册主要是cdev对象的初始化和注册，这个是每个”子”设备都需要进行的：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">cdev</span> <span class="title">dev</span>[<span class="title">dev_cnt</span>];</span> <span class="comment">/* 定义一个字符设备对象设备 */</span></span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; dev_cnt; i++)</span><br><span class="line">&#123;</span><br><span class="line">    dev[i].owner = THIS_MODULE;</span><br><span class="line">    <span class="comment">/* 初始化 cdev 对象, 给该对象添加操作函数集 */</span></span><br><span class="line">    cdev_init(&amp;dev[i], &amp;func_ops);</span><br><span class="line">    <span class="comment">/* 向 Linux 系统添加字符设备 (cdev结构体变量,将会被添加到一个hash链表中) */</span></span><br><span class="line">    <span class="comment">/* 会在 /proc/devices 中创建设备号和对应的名称记录(最终只会有一条主设备号的记录，但还是要分多次添加) */</span></span><br><span class="line">    cdev_add(&amp;dev2, devno + i, <span class="number">1</span>); <span class="comment">/* 此处是固定的一个一个添加 */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注销时候就是一个一个删除就行了：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 3.删除字符设备对象 cdev */</span></span><br><span class="line"><span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; dev_cnt; i++)</span><br><span class="line">&#123;</span><br><span class="line">    cdev_del(&amp;dev[i]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="1-3-类的创建与销毁"><a href="#1-3-类的创建与销毁" class="headerlink" title="1.3 类的创建与销毁"></a><font size=3>1.3 类的创建与销毁</font></h3><p>这些多个设备属于同一个类，我们只需要创建一个类就可以了：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 创建类（要注意无论是一个设备还是多个设备，类只有一个） */</span></span><br><span class="line">p_class = class_create(THIS_MODULE, NEWCHAR_DEV_NAME);</span><br></pre></td></tr></table></figure>

<p>删除时候也只需要删除一个类：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 删除类（只有一个类，删除一次即可） */</span></span><br><span class="line">class_destroy(p_class);</span><br></pre></td></tr></table></figure>

<h3 id="1-4-设备创建与销毁"><a href="#1-4-设备创建与销毁" class="headerlink" title="1.4 设备创建与销毁"></a><font size=3>1.4 设备创建与销毁</font></h3><p>因为我们是多个设备，所以每个设备都需要进行创建</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 创建设备(有几个设备，就创建几个) */</span></span><br><span class="line"><span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; dev_cnt; i++)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">/* 创建的设备为 /dev/dev_name */</span></span><br><span class="line">    device[i] = device_create(p_class, <span class="literal">NULL</span>, devno[i], <span class="literal">NULL</span>, <span class="string">&quot;%s%d&quot;</span>, NEWCHAR_DEV_NAME, i);&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>销毁的时候也要逐个销毁：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">/* 删除设备(多个设备，逐个进行删除) */</span></span><br><span class="line"><span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; dev_cnt; i++)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">/* 删除的是 /dev/dev_name */</span></span><br><span class="line">    device_destroy(p_class, devno[i]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="1-5-怎么区分不同的设备？"><a href="#1-5-怎么区分不同的设备？" class="headerlink" title="1.5 怎么区分不同的设备？"></a><font size=3>1.5 怎么区分不同的设备？</font></h3><p>还是一样的问题，之前我们是通过inode&rarr;i_rdev，也就是设备号来获取子设备号，然后找到对应的设备的缓冲区，理论上来说，多个cdev设备的时候，也可以通过这种方式，但是我没试。这次我们来使用inode的i_cdev成员。</p>
<p>inode中的i_cdev成员保存了对应字符设备结构体的地址，但是我们的虚拟设备是把cdev封装起来的一个结构体，例如：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 新字符设备的属性 */</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> _<span class="title">my_dev</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="comment">/* 1.设备号与设备数量 */</span></span><br><span class="line">    <span class="type">int</span> major;   <span class="comment">/* 主设备号：占高12位，用来表示驱动程序相同的一类设备，Linux系统中主设备号范围为 0~4095 */</span></span><br><span class="line">    <span class="type">int</span> minor;   <span class="comment">/* 次设备号：占低20位，用来表示被操作的哪个具体设备 */</span></span><br><span class="line">    <span class="type">dev_t</span> devno; <span class="comment">/* 新字符设备的设备号：由主设备号和次设备号组成 */</span></span><br><span class="line">    <span class="comment">/* 2.字符设备对象 */</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">cdev</span> <span class="title">mydev</span>;</span> <span class="comment">/* 定义一个字符设备对象设备 */</span></span><br><span class="line">    <span class="comment">/* 3.设备读写相关成员变量 */</span></span><br><span class="line">    <span class="type">char</span> mydev_buf[BUF_LEN]; <span class="comment">/* 读写缓冲区 */</span></span><br><span class="line">    <span class="type">int</span> curlen;              <span class="comment">/* 读写缓冲区中当前数据字节数 */</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 自动创建设备节点相关成员变量 */</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">device</span> *<span class="title">device</span>;</span>   <span class="comment">/* 设备 */</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="class"><span class="keyword">struct</span> _<span class="title">my_dev</span> <span class="title">g_my_dev</span>[<span class="title">NEWCHAR_DEV_CNT</span>];</span> <span class="comment">/* 定义新字符设备数组 */</span></span><br></pre></td></tr></table></figure>

<p>那我们要如何能够得到虚拟设备的数据缓冲区呢？为此，Linux提供了一个宏定义 <a target="_blank" rel="noopener" href="https://elixir.bootlin.com/linux/v4.19.71/source/include/linux/kernel.h#L990">container_of()</a>，该宏可以根据结构体的某个成员的地址， 来得到该结构体的地址。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * container_of - cast a member of a structure out to the containing structure</span></span><br><span class="line"><span class="comment"> * @ptr:	the pointer to the member.</span></span><br><span class="line"><span class="comment"> * @type:	the type of the container struct this is embedded in.</span></span><br><span class="line"><span class="comment"> * @member:	the name of the member within the struct.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> container_of(ptr, type, member) (&#123;				\</span></span><br><span class="line"><span class="meta">	void *__mptr = (void *)(ptr);					\</span></span><br><span class="line"><span class="meta">	BUILD_BUG_ON_MSG(!__same_type(*(ptr), ((type *)0)-&gt;member) &amp;&amp;	\</span></span><br><span class="line"><span class="meta">			 !__same_type(*(ptr), void),			\</span></span><br><span class="line"><span class="meta">			 <span class="string">&quot;pointer type mismatch in container_of()&quot;</span>);	\</span></span><br><span class="line"><span class="meta">	((type *)(__mptr - offsetof(type, member))); &#125;)</span></span><br></pre></td></tr></table></figure>

<p>该宏需要三个参数，分别是代表结构体成员的真实地址，结构体的类型以及结构体成员的名字。这个在这里就详细再去分析原理了，可以看后面参考资料的【1】和【2】。在sdev_open()函数中，我们需要通过inode的i_cdev成员，来得到对应的虚拟设备结构体，并保存到文件指针file的私有数据成员中。 假如，我们打开虚拟设备1，那么inode-&gt;i_cdev便指向了sdevice0的成员mydev，利用container_of宏， 我们就可以得到g_my_dev结构体的地址，也就可以操作对应的数据缓冲区了。</p>
<h2 id="2-demo实现-1"><a href="#2-demo实现-1" class="headerlink" title="2. demo实现"></a><font size=3>2. demo实现</font></h2><p>直接看gitee仓库吧：<a target="_blank" rel="noopener" href="https://gitee.com/sumumm/imx6ull-driver-demo/tree/master/04_chrdev_basic/10_chrdev_more_dev_mc">04_chrdev_basic&#x2F;10_chrdev_more_dev_mc · 苏木&#x2F;imx6ull-driver-demo - 码云 - 开源中国</a></p>
<details class="folding-tag" blue><summary> 点击查看详情 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/init.h&gt;</span> <span class="comment">/* module_init module_exit */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/kernel.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/module.h&gt;</span> <span class="comment">/* MODULE_LICENSE */</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/fs.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/cdev.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/uaccess.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;./timestamp_autogenerated.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;./version_autogenerated.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CHRDEV_NAME <span class="string">&quot;sdev&quot;</span>    <span class="comment">/* 设备名,cat /proc/devices 查看与设备号的对应关系 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CLASS_NAME  <span class="string">&quot;sclass&quot;</span>  <span class="comment">/* 类名，在 /sys/class 中显示的名称 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> DEVICE_NAME <span class="string">&quot;sdevice&quot;</span> <span class="comment">/* 设备节点名，在 /sys/class/class_name/ 中显示的名称以及 /dev/ 下显示的节点名 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> BUFSIZE     32        <span class="comment">/* 设置最大偏移量为32 */</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CHRDEV_CNT (2)        <span class="comment">/* 设备数量 */</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CMD_TEST0 _IO(<span class="string">&#x27;S&#x27;</span>, 0)</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CMD_TEST1 _IOW(<span class="string">&#x27;S&#x27;</span>, 1, int)</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CMD_TEST2 _IOR(<span class="string">&#x27;S&#x27;</span>, 2, int)</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CMD_TEST3 _IOW(<span class="string">&#x27;S&#x27;</span>, 3, int)</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> __<span class="title">CMD_TEST</span>&#123;</span></span><br><span class="line">	<span class="type">int</span> a;</span><br><span class="line">	<span class="type">int</span> b;</span><br><span class="line">	<span class="type">int</span> c;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 父设备号相关结构体，为了创建子设备号(子设备 0 的设备号与父设备号相同) </span></span><br><span class="line"><span class="comment"> *  父设备可以看做是代表了整个驱动程序，父设备下挂3个具体的设备</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> __<span class="title">MY_DEV_PARENT</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="comment">/* 1.设备号与设备数量 */</span></span><br><span class="line">    <span class="type">int</span> major;   <span class="comment">/* 主设备号：占高12位，用来表示驱动程序相同的一类设备，Linux系统中主设备号范围为 0~4095 */</span></span><br><span class="line">    <span class="type">int</span> minor;   <span class="comment">/* 次设备号：占低20位，用来表示被操作的哪个具体设备 */</span></span><br><span class="line">    <span class="type">dev_t</span> devno; <span class="comment">/* 新字符设备的设备号：由主设备号和次设备号组成    */</span></span><br><span class="line">    <span class="type">int</span> dev_cnt; <span class="comment">/* 次设备数量 */</span></span><br><span class="line">    <span class="comment">/* 2.自动创建设备节点相关成员变量 */</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="keyword">class</span> *<span class="keyword">class</span>;</span> <span class="comment">/* 类（无论几个次设备，这里的类只有一个，当然是同一类的情况下） */</span></span><br><span class="line">&#125;_MY_DEV_PARENT;</span><br><span class="line"></span><br><span class="line">_MY_DEV_PARENT parent_dev = &#123;</span><br><span class="line">    .major = <span class="number">0</span>,</span><br><span class="line">    .minor = <span class="number">0</span>,</span><br><span class="line">    .devno = <span class="number">0</span>,</span><br><span class="line">    .dev_cnt = CHRDEV_CNT,</span><br><span class="line">    .class = <span class="literal">NULL</span>,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> __<span class="title">CHAR_DEVICE</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="type">dev_t</span> dev_num;         <span class="comment">// 定义dev_t类型（32位大小）的变量dev_num,用来存放设备号</span></span><br><span class="line">    <span class="type">int</span> major;             <span class="comment">// 主设备号：占高12位，用来表示驱动程序相同的一类设备，Linux系统中主设备号范围为 0~4095</span></span><br><span class="line">    <span class="type">int</span> minor;             <span class="comment">// 次设备号：占低20位，用来表示被操作的哪个具体设备</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">cdev</span> <span class="title">s_cdev</span>;</span>    <span class="comment">// 定义cdev结构体类型的变量scdev</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="keyword">class</span> *<span class="keyword">class</span>;</span>   <span class="comment">// 定于struct class *类型结构体变量 class，表示要创建的类</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">device</span> *<span class="title">device</span>;</span> <span class="comment">// 设备</span></span><br><span class="line">    <span class="type">char</span> buf[BUFSIZE];     <span class="comment">// 设置数据存储数组mem</span></span><br><span class="line">&#125; _CHAR_DEVICE;</span><br><span class="line"></span><br><span class="line">_CHAR_DEVICE g_sdev[CHRDEV_CNT];  <span class="comment">//定义一个 g_sdev 结构体变量</span></span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="type">int</span> <span class="title function_">sdev_open</span><span class="params">(<span class="keyword">struct</span> inode *inode, <span class="keyword">struct</span> file *file)</span></span><br><span class="line">&#123;</span><br><span class="line">    printk(<span class="string">&quot;This is sdev_open!\n&quot;</span>);</span><br><span class="line">    file-&gt;private_data = (<span class="type">void</span> *)(container_of(inode-&gt;i_cdev, _CHAR_DEVICE, s_cdev));</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="type">ssize_t</span> <span class="title function_">sdev_read</span><span class="params">(<span class="keyword">struct</span> file *file, <span class="type">char</span> __user *buf, <span class="type">size_t</span> size, <span class="type">loff_t</span> *off)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="type">loff_t</span> offset = *off; <span class="comment">// 将读取数据的偏移量赋值给loff_t类型变量p</span></span><br><span class="line">    <span class="type">size_t</span> count = size;</span><br><span class="line">    _CHAR_DEVICE *pDev=(_CHAR_DEVICE *)file-&gt;private_data; <span class="comment">//在write函数中读取private_data</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (offset &gt; BUFSIZE)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (count &gt; BUFSIZE - offset)</span><br><span class="line">    &#123;</span><br><span class="line">        count = BUFSIZE - offset;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (copy_to_user(buf, pDev-&gt;buf + offset, count))</span><br><span class="line">    &#123; </span><br><span class="line">        <span class="comment">// 将mem中的值写入buf，并传递到用户空间</span></span><br><span class="line">        printk(<span class="string">&quot;copy_to_user error!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; BUFSIZE; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        printk(<span class="string">&quot;buf[%d] %c\n&quot;</span>, i, pDev-&gt;buf[i]); <span class="comment">// 将mem中的值打印出来</span></span><br><span class="line">    &#125;</span><br><span class="line">    printk(<span class="string">&quot;read offset is %llu, count is %d\n&quot;</span>, offset, count);</span><br><span class="line">    *off = *off + count; <span class="comment">// 更新偏移值</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> count;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="type">ssize_t</span> <span class="title function_">sdev_write</span><span class="params">(<span class="keyword">struct</span> file *file, <span class="type">const</span> <span class="type">char</span> __user *buf, <span class="type">size_t</span> size, <span class="type">loff_t</span> *off)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="type">loff_t</span> offset = *off; <span class="comment">// 将读取数据的偏移量赋值给loff_t类型变量p</span></span><br><span class="line">    <span class="type">size_t</span> count = size;</span><br><span class="line">    _CHAR_DEVICE *pDev=(_CHAR_DEVICE *)file-&gt;private_data; <span class="comment">//在write函数中读取private_data</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (offset &gt; BUFSIZE)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (count &gt; BUFSIZE - offset)</span><br><span class="line">    &#123;</span><br><span class="line">        count = BUFSIZE - offset;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (copy_from_user(pDev-&gt;buf + offset, buf, count))</span><br><span class="line">    &#123; </span><br><span class="line">        <span class="comment">// 将buf中的值，从用户空间传递到内核空间</span></span><br><span class="line">        printk(<span class="string">&quot;copy_to_user error \n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; BUFSIZE; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        printk(<span class="string">&quot;buf[%d] %c\n&quot;</span>, i, pDev-&gt;buf[i]); <span class="comment">// 将mem中的值打印出来</span></span><br><span class="line">    &#125;</span><br><span class="line">    printk(<span class="string">&quot;write offset is %llu, count is %d\n&quot;</span>, offset, count); <span class="comment">// 打印写入的值</span></span><br><span class="line">    *off = *off + count;                         <span class="comment">// 更新偏移值</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> count;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="type">int</span> <span class="title function_">sdev_release</span><span class="params">(<span class="keyword">struct</span> inode *inode, <span class="keyword">struct</span> file *file)</span></span><br><span class="line">&#123;</span><br><span class="line">    printk(<span class="string">&quot;This is sdev_release!\n&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="type">loff_t</span> <span class="title function_">sdev_llseek</span><span class="params">(<span class="keyword">struct</span> file *file, <span class="type">loff_t</span> offset, <span class="type">int</span> whence)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">loff_t</span> new_offset = <span class="number">0</span>; <span class="comment">// 定义loff_t类型的新的偏移值</span></span><br><span class="line">    <span class="keyword">switch</span> (whence)    <span class="comment">// 对lseek函数传递的whence参数进行判断</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">case</span> SEEK_SET:</span><br><span class="line">            <span class="keyword">if</span> (offset &lt; <span class="number">0</span> || offset &gt; BUFSIZE)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">return</span> -EINVAL; <span class="comment">// EINVAL=22 表示无效参数</span></span><br><span class="line">            &#125;</span><br><span class="line">            new_offset = offset; <span class="comment">// 如果whence参数为SEEK_SET，则新偏移值为offset</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> SEEK_CUR:</span><br><span class="line">            <span class="keyword">if</span> ((file-&gt;f_pos + offset &lt; <span class="number">0</span>) || (file-&gt;f_pos + offset &gt; BUFSIZE))</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">return</span> -EINVAL;</span><br><span class="line">            &#125;</span><br><span class="line">            new_offset = file-&gt;f_pos + offset; <span class="comment">// 如果whence参数为SEEK_CUR，则新偏移值为file-&gt;f_pos + offset，file-&gt;f_pos为当前的偏移值</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> SEEK_END:</span><br><span class="line">            <span class="keyword">if</span> (file-&gt;f_pos + offset &lt; <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">return</span> -EINVAL;</span><br><span class="line">            &#125;</span><br><span class="line">            new_offset = BUFSIZE + offset; <span class="comment">// 如果whence参数为SEEK_END，则新偏移值为BUFSIZE + offset，BUFSIZE为最大偏移量</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    file-&gt;f_pos = new_offset; <span class="comment">// 更新file-&gt;f_pos偏移值</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> new_offset;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="type">long</span> <span class="title function_">sdev_ioctl</span><span class="params">(<span class="keyword">struct</span> file *file, <span class="type">unsigned</span> <span class="type">int</span> cmd, <span class="type">unsigned</span> <span class="type">long</span> arg)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> val = <span class="number">0</span>;<span class="comment">//定义 int 类型向应用空间传递的变量 val</span></span><br><span class="line">    <span class="keyword">switch</span>(cmd)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">case</span> CMD_TEST0:</span><br><span class="line">            printk(<span class="string">&quot;this is CMD_TEST0\n&quot;</span>);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> CMD_TEST1:</span><br><span class="line">            printk(<span class="string">&quot;this is CMD_TEST1\n&quot;</span>);</span><br><span class="line">            printk(<span class="string">&quot;arg is %ld\n&quot;</span>,arg);<span class="comment">//打印应用空间传递来的 arg 参数</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> CMD_TEST2:</span><br><span class="line">            val = <span class="number">1</span>;<span class="comment">//将要传递的变量 val 赋值为 1</span></span><br><span class="line">            printk(<span class="string">&quot;this is CMD_TEST2\n&quot;</span>);</span><br><span class="line">            <span class="keyword">if</span>(copy_to_user((<span class="type">int</span> *)arg, &amp;val, <span class="keyword">sizeof</span>(val)) != <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="comment">//通过 copy_to_user 向用户空间传递数据</span></span><br><span class="line">                printk(<span class="string">&quot;copy_to_user error \n&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> CMD_TEST3:</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="class"><span class="keyword">struct</span> __<span class="title">CMD_TEST</span> <span class="title">cmd_test3</span> =</span> &#123;<span class="number">0</span>&#125;;</span><br><span class="line">            <span class="keyword">if</span> (copy_from_user(&amp;cmd_test3, (<span class="type">int</span> *)arg, <span class="keyword">sizeof</span>(cmd_test3)) != <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                printk(<span class="string">&quot;copy_from_user error\n&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            printk(<span class="string">&quot;cmd_test3.a = %d\n&quot;</span>, cmd_test3.a);</span><br><span class="line">            printk(<span class="string">&quot;cmd_test3.b = %d\n&quot;</span>, cmd_test3.b);</span><br><span class="line">            printk(<span class="string">&quot;cmd_test3.c = %d\n&quot;</span>, cmd_test3.c);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="class"><span class="keyword">struct</span> <span class="title">file_operations</span> <span class="title">cdev_ops</span> =</span> &#123;</span><br><span class="line">    .owner = THIS_MODULE,<span class="comment">//将owner字段指向本模块，可以避免在模块的操作正在被使用时卸载该模块</span></span><br><span class="line">	.open = sdev_open,</span><br><span class="line">	.read = sdev_read,</span><br><span class="line">	.write = sdev_write,</span><br><span class="line">	.release = sdev_release,</span><br><span class="line">    .llseek = sdev_llseek,</span><br><span class="line">    .unlocked_ioctl = sdev_ioctl,</span><br><span class="line">&#125;; <span class="comment">// 定义file_operations结构体类型的变量 cdev_ops</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 模块入口函数</span></span><br><span class="line"><span class="type">static</span> <span class="type">int</span> __init <span class="title function_">chrdev_more_dev_mc_demo_init</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="type">int</span> ret = <span class="number">0</span>;              <span class="comment">// 定义int类型的变量ret，用来判断函数返回值</span></span><br><span class="line">    printk(<span class="string">&quot;*** [%s:%d]Build Time: %s %s, git version:%s ***\n&quot;</span>, __FUNCTION__,</span><br><span class="line">           __LINE__, KERNEL_KO_DATE, KERNEL_KO_TIME, KERNEL_KO_VERSION);</span><br><span class="line">    printk(<span class="string">&quot;chrdev_more_dev_mc_demo module init!\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    ret = alloc_chrdev_region(&amp;parent_dev.devno, <span class="number">0</span>, parent_dev.dev_cnt, CHRDEV_NAME); <span class="comment">// 自动获取设备号，设备名为chrdev_name</span></span><br><span class="line">    <span class="keyword">if</span> (ret &lt; <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        printk(<span class="string">&quot;alloc_chrdev_region is error!\n&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    printk(<span class="string">&quot;alloc_register_region is ok!\n&quot;</span>);</span><br><span class="line">    parent_dev.major = MAJOR(parent_dev.devno); <span class="comment">// 使用MAJOR()函数获取主设备号</span></span><br><span class="line">    parent_dev.minor = MINOR(parent_dev.devno); <span class="comment">// 使用MINOR()函数获取次设备号</span></span><br><span class="line">    printk(<span class="string">&quot;parent_dev major is %d, minor is %d !\n&quot;</span>, parent_dev.major, parent_dev.minor);</span><br><span class="line">    <span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; parent_dev.dev_cnt; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        g_sdev[i].dev_num = parent_dev.devno + i; <span class="comment">/* devno + i 即可得到连续申请的设备号 */</span></span><br><span class="line">        g_sdev[i].major = MAJOR(g_sdev[i].dev_num); <span class="comment">/* 获取分配号的主设备号 */</span></span><br><span class="line">        g_sdev[i].minor = MINOR(g_sdev[i].dev_num); <span class="comment">/* 获取分配号的次设备号 */</span></span><br><span class="line"></span><br><span class="line">        cdev_init(&amp;g_sdev[i].s_cdev, &amp;cdev_ops); <span class="comment">// 使用cdev_init()函数初始化g_sdev.s_cdev结构体，并链接到 cdev_ops 结构体</span></span><br><span class="line">        g_sdev[i].s_cdev.owner = THIS_MODULE;    <span class="comment">// 将owner字段指向本模块，可以避免在模块的操作正在被使用时卸载该模块</span></span><br><span class="line">        ret = cdev_add(&amp;g_sdev[i].s_cdev, g_sdev[i].dev_num, <span class="number">1</span>); <span class="comment">// 使用cdev_add()函数进行字符设备的添加</span></span><br><span class="line">        <span class="keyword">if</span> (ret &lt; <span class="number">0</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            printk(<span class="string">&quot;cdev_add is error !\n&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        printk(<span class="string">&quot;cdev_add dev %d is ok !\n&quot;</span>, i);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//这几个设备都属于同一类，创建一个class</span></span><br><span class="line">    parent_dev.class = class_create(THIS_MODULE, CLASS_NAME); <span class="comment">// 使用class_create进行类的创建，类名称为 class_dev</span></span><br><span class="line">    <span class="comment">//创建设备</span></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; parent_dev.dev_cnt; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        g_sdev[i].class = parent_dev.class;<span class="comment">//这parent_dev.dev_cnt个设备属于同一个类</span></span><br><span class="line">        g_sdev[i].device = device_create(g_sdev[i].class, <span class="literal">NULL</span>, g_sdev[i].dev_num, <span class="literal">NULL</span>, <span class="string">&quot;%s%d&quot;</span>, DEVICE_NAME, i); <span class="comment">// 使用device_create进行设备的创建，设备名称为 device_dev</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 模块出口函数</span></span><br><span class="line"><span class="type">static</span> <span class="type">void</span> __exit <span class="title function_">chrdev_more_dev_mc_demo_exit</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">// 需要注意的是， 字符设备的注册要放在申请字符设备号之后，</span></span><br><span class="line">    <span class="comment">// 字符设备的删除要放在释放字符驱动设备号之前。</span></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; parent_dev.dev_cnt; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">/* 删除的是 /dev/dev_name */</span></span><br><span class="line">        device_destroy(parent_dev.class, g_sdev[i].dev_num);</span><br><span class="line">        printk(<span class="string">&quot;g_sdev[%d]: [/dev/%s%d] has been deleted!\n&quot;</span>, i, DEVICE_NAME, i);</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">// 删除的是 /sys/class/class_name</span></span><br><span class="line">    class_destroy(parent_dev.class);           <span class="comment">// 删除创建的类</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 删除字符设备对象 cdev */</span></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; parent_dev.dev_cnt; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        cdev_del(&amp;g_sdev[i].s_cdev);<span class="comment">// 使用cdev_del()函数进行字符设备的删除</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 注销设备号（将会删除 /proc/devices 中的设备号和对应的名称记录) */</span></span><br><span class="line">    unregister_chrdev_region(parent_dev.devno, parent_dev.dev_cnt);</span><br><span class="line">    printk(<span class="string">&quot;chrdev_more_dev_mc_demo exit!\n&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">module_init(chrdev_more_dev_mc_demo_init); <span class="comment">// 将__init定义的函数指定为驱动的入口函数</span></span><br><span class="line">module_exit(chrdev_more_dev_mc_demo_exit); <span class="comment">// 将__exit定义的函数指定为驱动的出口函数</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 模块信息(通过 modinfo chrdev_more_dev_mc_demo 查看) */</span></span><br><span class="line">MODULE_LICENSE(<span class="string">&quot;GPL v2&quot;</span>);            <span class="comment">/* 源码的许可证协议 */</span></span><br><span class="line">MODULE_AUTHOR(<span class="string">&quot;sumu&quot;</span>);               <span class="comment">/* 字符串常量内容为模块作者说明 */</span></span><br><span class="line">MODULE_DESCRIPTION(<span class="string">&quot;Description&quot;</span>);   <span class="comment">/* 字符串常量内容为模块功能说明 */</span></span><br><span class="line">MODULE_ALIAS(<span class="string">&quot;module&#x27;s other name&quot;</span>); <span class="comment">/* 字符串常量内容为模块别名 */</span></span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h2 id="3-开发板测试-1"><a href="#3-开发板测试-1" class="headerlink" title="3. 开发板测试"></a><font size=3>3. 开发板测试</font></h2><ul>
<li>（1）加载驱动</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">insmod chrdev_more_dev_mc_demo.ko</span><br></pre></td></tr></table></figure>

<ul>
<li>（2）查看设备节点</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ls /dev/sdevice* -alh</span><br></pre></td></tr></table></figure>

<p>会看到有如下打印信息：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">crw-rw----    1 0        root      246,   0 Jan  1 00:00 /dev/sdevice0</span><br><span class="line">crw-rw----    1 0        root      246,   1 Jan  1 00:00 /dev/sdevice1</span><br></pre></td></tr></table></figure>

<p>在创建设备节点的时候命名就是&#x2F;dev&#x2F;sdeviceN，所以这里是0和1两个设备节点，他们会对应不同的缓冲区。</p>
<ul>
<li>（3）向设备节点写入数据</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">echo 123456789 &gt; /dev/sdevice0</span><br><span class="line">echo 987654321 &gt; /dev/sdevice1</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">或者使用应用测试程序</span></span><br><span class="line">./xxx_demo_app.out /dev/sdevice 1 x # 从x位置读取</span><br><span class="line">./xxx_demo_app.out /dev/sdevice 2 x # 从x位置写入</span><br><span class="line">./xxx_demo_app.out /dev/sdevice 3 x # x为任意值</span><br></pre></td></tr></table></figure>

<ul>
<li>（4）从设备节点读取数据</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">cat /dev/sdevice0</span><br><span class="line">cat /dev/sdevice1</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">或者使用应用测试程序</span></span><br><span class="line">./xxx_demo_app.out /dev/sdevice 1 x # 从x位置读取</span><br><span class="line">./xxx_demo_app.out /dev/sdevice 2 x # 从x位置写入</span><br><span class="line">./xxx_demo_app.out /dev/sdevice 3 x # x为任意值</span><br></pre></td></tr></table></figure>



<blockquote>
<p>参考资料</p>
<p>【1】<a target="_blank" rel="noopener" href="https://www.jb51.net/article/222490.htm">Linux内核宏Container_Of的详细解释_Linux_脚本之家</a></p>
<p>【2】<a target="_blank" rel="noopener" href="https://www.cnblogs.com/-Donge/p/17900065.html">【Linux API 揭秘】container_of函数详解 - 董哥聊技术 - 博客园</a></p>
<p>【3】<a target="_blank" rel="noopener" href="https://gcc.gnu.org/onlinedocs/gcc/Typeof.html">Typeof (Using the GNU Compiler Collection (GCC))</a></p>
<p>【4】<a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/54932270">linux 内核宏container_of剖析 - 知乎</a></p>
</blockquote>

    </div>

    
    
    

    <footer class="post-footer">




    <div>
        
            <div style="text-align:center;color: #ccc;font-size:14px;">
            ----------本文结束
            <i class="fas fa-fan fa-spin" style="color: #FF1493; font-size: 1rem"></i>
            感谢您的阅读----------
            </div>
        
    </div>





  
  <div class="my_post_copyright"> 
    <p><span>文章标题:</span><a href="/post/c439ab2a.html">LV06-03-chrdev-08-1个驱动兼容多个设备</a></p>
    <p><span>文章作者:</span><a href="/" title="欢迎访问 《苏木》 的学习笔记">苏木</a></p>
    <p><span>发布时间:</span>2024年12月26日 - 22:38</p>
    <p><span>最后更新:</span>2025年06月14日 - 00:25</p>
    <p><span>原始链接:</span><a href="/post/c439ab2a.html" title="LV06-03-chrdev-08-1个驱动兼容多个设备">https://sumumm.github.io/post/c439ab2a.html</a></p>
    <p><span>许可协议:</span><i class="fab fa-creative-commons"></i> <a rel="license" href= "https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
  </div>
  


          <div class="post-tags">
              <a href="/tags/LV06-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/" rel="tag"><i class="fa fa-tag"></i> LV06-驱动开发</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/post/e27975db.html" rel="prev" title="05GitHubActions-readme">
                  <i class="fa fa-angle-left"></i> 05GitHubActions-readme
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/post/54240ae3.html" rel="next" title="LV06-03-chrdev-07-字符设备基本原理">
                  LV06-03-chrdev-07-字符设备基本原理 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2017 – 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">苏木</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">3.7m</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">225:26</span>
  </span>
</div>




    <span id="sitetime"></span>
    <script defer language=javascript>
        function siteTime()
        {
            window.setTimeout("siteTime()", 1000);
            var seconds = 1000;
            var minutes = seconds * 60;
            var hours = minutes * 60;
            var days = hours * 24;
            var years = days * 365;
            var today = new Date();
            var todayYear = today.getFullYear();
            var todayMonth = today.getMonth()+1;
            var todayDate = today.getDate();
            var todayHour = today.getHours();
            var todayMinute = today.getMinutes();
            var todaySecond = today.getSeconds();
            /*==================================================
            Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
            year        - 作为date对象的年份，为4位年份值
            month       - 0-11之间的整数，做为date对象的月份
            day         - 1-31之间的整数，做为date对象的天数
            hours       - 0(午夜24点)-23之间的整数，做为date对象的小时数
            minutes     - 0-59之间的整数，做为date对象的分钟数
            seconds     - 0-59之间的整数，做为date对象的秒数
            microseconds - 0-999之间的整数，做为date对象的毫秒数
            ==================================================*/
            var t1 = Date.UTC(2017, 
                              5, 
                              19, 
                              0, 
                              0, 
                              0); //北京时间
            var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
            var diff = t2-t1;
            var diffYears = Math.floor(diff/years);
            var diffDays = Math.floor((diff/days)-diffYears*365);
            var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
            var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
            var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
            document.getElementById("sitetime").innerHTML="已在这里 "+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
        }
        siteTime();
    </script>



    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.umd.js" integrity="sha256-ytMJGN3toR+a84u7g7NuHm91VIR06Q41kMWDr2pq7Zo=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>


  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


 
        <div id="click-show-text"
            data-mobile = false
            data-text = 富强,民主,文明,和谐,自由,平等,公正,法制,爱国,敬业,诚信,友善
            data-fontsize = 15px
            data-random= false>
        </div>
       

      
        <script async src=https://cdn.jsdelivr.net/npm/hexo-next-mouse-effect@latest/click/showText.js></script>
      

      
    




    <script async src="/js/fancybox_param.js"></script>





<!-- APlayer本体 -->



</body>
</html>
